<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增分类</el-button>
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="分类名称">
            <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable />
          </el-form-item>
          <el-form-item label="分类级别">
            <el-select v-model="queryParams.levelId" filterable clearable placeholder="请选择级别">
              <el-option v-for="(item) in categoryLevel" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>

    </el-row>
    <el-table v-loading="loading" :data="categoryTableData">
      <el-table-column label="编号" align="center" prop="id" min-width="50" />
      <el-table-column label="分类名称" align="center" prop="name" min-width="180" />
      <el-table-column label="分类级别" align="center" min-width="180">
        <template #default="scope">
          <span v-if="scope.row.levelId == 1">一级分类</span>
          <span v-else>二级分类</span>
        </template>
      </el-table-column>
      <el-table-column label="父级分类" align="center" prop="parentName" min-width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="180" />
      <el-table-column label="操作" align="center" min-width="160" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link size="small" type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link size="small" type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.size"
      @pagination="getProductCategoryLists" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="dialogTitleText" v-model="open" width="600px" append-to-body @close="handleClose()">
      <el-form v-if="dialogTitleText == '编辑分类' ? false : true" ref="addFormRef" :model="form" :rules="rules"
        label-width="120px">
        <el-form-item label="分类名称:" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类级别:" prop="categoryLevel">
          <el-select v-model="form.categoryLevel" filterable clearable placeholder="请选择级别">
            <el-option v-for="(item) in categoryLevel" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="一级分类:" v-if="onelevelIsShow" prop="onelevelValue">
          <el-select v-model="form.onelevelValue" filterable clearable placeholder="请选择级别">
            <el-option v-for="(item) in allCategoryoneLevel" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <el-form v-else ref="editFormRef" :model="editForm" :rules="rules" label-width="120px">
        <el-form-item label="分类名称:" prop="categoryName">
          <el-input v-model="editForm.categoryName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="分类级别:" prop="categoryLevel">
          <el-input disabled v-model="editForm.categoryLevel" placeholder="请输入商品零售价"></el-input>
         
        </el-form-item>
        <el-form-item label="父级分类:" prop="parentCategory">
          <el-input disabled v-model="editForm.parentCategory" placeholder="请输入商品零售价"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-loading="loading">
          <el-button @click="open = false">取 消</el-button>
          <el-button type="primary" @click="submitForm()">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import UpFile from "@/components/upFile/index.vue";
import { addFile, upFileReq, getImg, delFile } from "@/api/components/index.js";
// import { getProductList, addProduct,editProduct,delProduct } from "@/api/product/index.js"
import { getCategorylevel, getCategoryList, delCategoryList, addCategory,getAllCategoryList,editCategory } from '@/api/productCategory/index.js'
import { reactive, watch } from "vue";

const { proxy } = getCurrentInstance();
const open = ref(false);
const loading = ref(false);
const fileList = ref([]);
const upFileRef = ref(null);
const dialogTitleText = ref('')
const total = ref(0);
const onelevelIsShow = ref(false);
const addFormRef = ref(null); 
const editFormRef = ref(null); 

const form = reactive({
  categoryName: '',
  categoryLevel: '',
  onelevelValue: ''
})
const rules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
  ],
  categoryLevel: [
    { required: true, message: '请选择分类级别', trigger: 'blur' },
  ],
  onelevelValue: [
    { required: true, message: '请选择一级分类', trigger: 'blur' },
  ]
};
const currentId = ref('')







let fileId;
const data = reactive({
  // form: {
  //   categoryName: '',
  //   categoryLevel: '',
  //   onelevelValue: ''
  // },
  editForm: {
    categoryName: '',
    categoryLevel: '',
    parentCategory: '',
  },
  queryParams: {
    page: 1,
    size: 10,
    name: '',
    levelId: ''
  },
  queryParams2: {
    page: 1,
    size: 10000,
    name: '',
    levelId: ''
  },
  moreArr: [],
  categoryLevel: [],
  categoryTableData: [],
  allCategoryoneLevel: []
});
const { allCategoryoneLevel, categoryTableData, categoryLevel, editForm, queryParams,queryParams2 } = toRefs(data);
function handleAdd() {
  open.value = true;
  dialogTitleText.value = '新增分类'

}
async function handleUpdate(row) {
  console.log('当亲啊含',row);
  open.value = true;
  // fileId = row.id;
  // nextTick(() => {
  //   fileList.value = imgEvent(row);
  // })
  dialogTitleText.value = '编辑分类'
  currentId.value = row.id
  editForm.value.categoryName = row.name
  editForm.value.categoryLevel = row.levelId == 1 ? '一级分类' : '二级分类'
  editForm.value.parentCategory = row.parentName





}
async function submitForm() {
  if (dialogTitleText.value == '编辑分类') {
    await proxy.$refs["editFormRef"].validate();
    let params = {
      name: editForm.value.categoryName,
      id:currentId.value
    }
    editCategory(params).then(res => {
      if(res.code == 1){
        proxy.$modal.msgSuccess("修改成功");
        open.value = false
        getProductCategoryLists()
      }
    })
 
  } else {
    await proxy.$refs["addFormRef"].validate();
    let params = {
      name:form.categoryName,
      levelId:form.categoryLevel,
      parentId:form.onelevelValue
    }
    addCategory(params).then(res => {
      if(res.code == 1){
        proxy.$modal.msgSuccess("新增成功");
        open.value = false
        getProductCategoryLists()
      }
    })

  }

}
async function handleDelete(row) {
  await proxy.$modal.confirm("确认删除当前分类数据吗？");
  await delCategoryList({ id: row.id });
  proxy.$modal.msgSuccess("删除成功");
  getProductCategoryLists();

}
async function getProductCategoryLists() {
  try {
    loading.value = true;

    const { data, total: totalAll } = await getCategoryList(queryParams.value);
    total.value = totalAll;
    categoryTableData.value = data;
    // categoryTableData.value.forEach(ele => {
    //   ele.categoryLevel = ele.cagegoryId == '1' ? '生活衣装' : '体育用品'
    //   ele.price = ele.price
    //   ele.vipPrice = ele.vipPrice
    //   ele.cuxiaoPrice = ele.cuxiaoPrice

    // })
  } finally {
    loading.value = false;
  }
}
async function getCategoryLevelData() {
  try {
    loading.value = true;
    const { data } = await getCategorylevel({ type: 'productCategory' });
    data.forEach(ele => {
      ele.label = ele.dictLabel
      ele.value = ele.dictValue
      categoryLevel.value.push(ele)
      categoryLevel.value.sort((a, b) => Number(a.value) - Number(b.value))
    })
  } finally {
    loading.value = false;
  }
}
async function getAllCategoryData() {
  try {
    // loading.value = true;
    const { data } = await getAllCategoryList(queryParams2.value);
    allCategoryoneLevel.value = []

    data.forEach(ele => {
      if (ele.levelId == 1) {
        allCategoryoneLevel.value.push(ele)
      }
    })
    allCategoryoneLevel.value.forEach(ele => {
      ele.label = ele.name
      ele.value = ele.id
    })
    console.log('所有一级分类', allCategoryoneLevel.value)


  } finally {
    // loading.value = false;
  }
}


function handleQuery() {
  queryParams.value.page = 1;
  getProductCategoryLists();
}
function imgEvent(row) {
  try {
    return JSON.parse(row.val)
  } catch (e) {
    return []
  }
}
function handleClose() {
  this.form.categoryName = ''
  this.form.categoryLevel = ''
  this.form.onelevelValue = ''

}
function addProductCategory() {

}
// getImgApi();
getProductCategoryLists()
getCategoryLevelData()

watch(() => form.categoryLevel, (newVal, oldVal) => {
  if (newVal == 2) {
    getAllCategoryData()
    onelevelIsShow.value = true
  } else {
    onelevelIsShow.value = false
  }
}, {
  deep: true, // 由于我们只观察一个属性，所以不需要深度观察  
  immediate: true, // 初始化时不立即调用回调函数  
})
</script>

<style scoped lang="scss">
.flex-box {
  text-align: center;
}

.img-box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  overflow: auto;

  >div {
    margin: 0 5px;
  }
}
</style>